import { defineStore } from 'pinia';
import { login, LoginData } from '@/api/user';
import {
  setToken,
  setListNumber,
  setName,
  setUserJob,
  setUserUnits,
  setUserUnitsNumber,
  clearToken,
  clearListNumber,
  clearName,
  clearUserJob,
  clearUserUnits,
  clearUserUnitsNumber,
} from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: undefined,
    username: undefined,
    userCode: undefined,
    avatar: undefined,
    deptCode: undefined,
    address: undefined,
    email: undefined,
    deptId: undefined,
    mobile: undefined,
    title: undefined,
    // 密级
    secretLevel: undefined,
    role: '',
    // 路由权限
    menus: [],
    // 按钮权限
    permissions: [],
    roles: [],
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // // Get user's information
    // async info() {
    //   const res = await getUserInfo();
    //   this.setInfo(res.data);
    // },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res: any = await login(loginForm);
        setToken('admin');
        setListNumber(res.responseBody);
        setName(res.responseBody.account);
        setUserJob(res.responseBody.empinfoid);
        setUserUnits(
          res.responseBody.empinfoDTOList[0].departmentDTOList[0].text
        );
        setUserUnitsNumber(res.responseBody.empinfoDTOList[0].departid);
      } catch (err) {
        clearToken();
        clearListNumber();
        clearName();
        clearUserJob();
        clearUserUnits();
        clearUserUnitsNumber();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        // await userLogout();
        clearToken();
        clearListNumber();
        clearName();
        clearUserJob();
        clearUserUnits();
        clearUserUnitsNumber();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
